package com.eve.eplus.main;

import java.io.File;
import java.io.IOException;
import java.util.Random;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.eve.eplus.R;
import com.eve.eplus.common.activity.BaseActivity;
import com.eve.eplus.common.app.BaseApplication;
import com.eve.eplus.common.app.Configuration;
import com.eve.eplus.common.app.Constants;
import com.eve.eplus.common.app.SettingConstants;
import com.eve.eplus.common.tools.ComImgTools;
import com.eve.eplus.common.tools.ComTimeTools;
import com.eve.eplus.common.tools.ConfigurationTools;
import com.eve.eplus.common.tools.LogTools;
import com.eve.eplus.common.view.ComDialogTools;
import com.eve.eplus.common.view.ComToastTools;
import com.eve.eplus.main.logic.SettingUtility;

public class ShareActivity extends BaseActivity {
	private Context mContext = ShareActivity.this;
	private LinearLayout btnSend, btnVoice, btnPic, btnTrends, btnClean;
	private ImageView ivPic;
	private EditText edtContent;
	private TextView tvNum;
	private LayoutInflater inflater;
	private Dialog mDialog;

	private String picPath;// 图片文件路径
	private static final int PHOTO_WITH_CAMERA = 1010;// 拍摄照片
	private static final int PHOTO_WITH_DATA = 1020;// 从SD中得到照片
	private static final File PHOTO_DIR = new File(Configuration.PHOTO_DIR);// 拍摄照片存储的文件夹路劲
	private File captureFile;// 拍摄的照片文件

	private boolean hasPic = false;// 是否含有图片
	private String[] msgHint;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home_share_main);
		msgHint=getResources().getStringArray(R.array.send_msg_hint_array);
		initView();
		
		
		//读取草稿
		edtContent.setText(ConfigurationTools.getInstance(mContext).getString(Constants.SAVED_MSG));
		//设置读取草稿之后的光标
		Editable edit = edtContent.getEditableText();// 获取EditText的文字
		edtContent.setSelection(edit.length());
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if(edtContent.getText().toString().length()>0){
			ComDialogTools.showConfirmDialog(mContext, "提示", "保存", "不保存", "是否保存未发的微薄内容？", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					ConfigurationTools.getInstance(mContext).putString(Constants.SAVED_MSG, edtContent.getText().toString());
					finish();
				}
			}, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
		}else{
			ConfigurationTools.getInstance(mContext).putString(Constants.SAVED_MSG, "");
			super.onBackPressed();
		}
			
	}

	private void initView() {
		btnSend = (LinearLayout) findViewById(R.id.send);
		btnVoice = (LinearLayout) findViewById(R.id.voice);
		btnPic = (LinearLayout) findViewById(R.id.pic);
		btnTrends = (LinearLayout) findViewById(R.id.call);
		btnClean = (LinearLayout) findViewById(R.id.cleanAll);
		edtContent = (EditText) findViewById(R.id.edittext);
		tvNum = (TextView) findViewById(R.id.editNum);
		ivPic = (ImageView) findViewById(R.id.picimg);

		btnSend.setOnClickListener(onClickListener);
		btnVoice.setOnClickListener(onClickListener);
		btnPic.setOnClickListener(onClickListener);
		btnTrends.setOnClickListener(onClickListener);
		btnClean.setOnClickListener(onClickListener);
		edtContent.addTextChangedListener(textWatcher);

		hasPic = false;
		
		/**
		 * 显示随机格言
		 */
		Random r=new Random();
		edtContent.setHint(msgHint[r.nextInt(msgHint.length)]);
	}

	/**
	 * 文字变化监听事件
	 */
	TextWatcher textWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			int len = edtContent.getText().toString().length();
			String slen = String.valueOf(140 - len);
			tvNum.setText(slen);
			if (140 - len <= 0) {
				tvNum.setTextColor(Color.RED);
			} else {
				tvNum.setTextColor(Color.DKGRAY);
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub

		}

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub

		}
	};

	/**
	 * 按钮点击监听事件
	 */
	OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.send:
				send();
				break;

			case R.id.voice:

				break;

			case R.id.pic:
				if (hasPic) {
					picPath = null;
					ivPic.setBackgroundResource(R.drawable.share_pic);
					hasPic = false;
				} else {
					getPic();
				}
				break;

			case R.id.call:

			{
				int index = edtContent.getSelectionStart();
				Editable edit = edtContent.getEditableText();// 获取EditText的文字
				if (index < 0 || index >= edit.length()) {
					edit.append("##");
				} else {
					edit.insert(index, "##");// 光标所在位置插入文字
				}
				edtContent.setSelection(edit.length() - 1);
			}
			break;
			case R.id.cleanAll:

				ComDialogTools.showConfirmDialog(mContext, "提示", "清空", "取消",
						"确认清空文字内容？", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						// TODO Auto-generated method stub
						edtContent.setText("");
						dialog.dismiss();
					}
				}, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});
				break;
			default:
				break;
			}

		}
	};

	/**
	 * 发送微博
	 */
	protected void send() {
		Animation cycleAnim = AnimationUtils.loadAnimation(mContext,
				R.anim.sendbtn_anim);
		String content = edtContent.getText().toString();
		if (content.length() == 0 && picPath != null)
			content = "分享图片";
		if (content.length() > 140) {
			btnSend.startAnimation(cycleAnim);
			ComToastTools.ShowMsg(mContext, "已超过" + (content.length() - 140)
					+ "个字", "l");
		} else if (content.length() == 0) {
			btnSend.startAnimation(cycleAnim);
			ComToastTools.ShowMsg(mContext, "请输入微博内容", "l");
		} else {

			BaseApplication.mShareObj = mContext;
			Intent intent = new Intent(mContext, SendMsgActivity.class);
			intent.putExtra(Constants.SNS_SEND_CONTENT, content);
			intent.putExtra(Constants.SNS_SEND_PICURI, picPath);
			startActivity(intent);
		}

	}

	/**
	 * 获取图片
	 */
	protected void getPic() {
		inflater = getLayoutInflater();
		View layout = inflater.inflate(R.layout.activity_home_share_takepic,
				(ViewGroup) findViewById(R.id.dialog));
		layout.findViewById(R.id.iv_data).setOnClickListener(
				onClickListenerInDialog);
		layout.findViewById(R.id.iv_camera).setOnClickListener(
				onClickListenerInDialog);
		mDialog = new Dialog(mContext, R.style.dialog);
		mDialog.setContentView(layout);
		mDialog.show();

	}

	/**
	 * 对话框的点击事件
	 */
	OnClickListener onClickListenerInDialog = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.iv_camera:
				String status = Environment.getExternalStorageState();
				if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
					Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					captureFile = new File(PHOTO_DIR,
							ComTimeTools.getTime("'IMG'_yyyyMMdd_HHmmss")
							+ ".jpg");
					try {
						if (SettingUtility.getCameraSaveSetting() == SettingConstants.CAMERA_SAVE_TRUE)
							captureFile.createNewFile();
						i.putExtra(MediaStore.EXTRA_OUTPUT,
								Uri.fromFile(captureFile));// 将拍摄的照片信息存到capturefile中
					} catch (IOException e) {
						e.printStackTrace();
					}

					startActivityForResult(i, PHOTO_WITH_CAMERA);// 用户点击了从照相机获取
				} else {
					ComToastTools.ShowMsg(mContext, "没有SD卡", "l");
				}
				break;

			case R.id.iv_data:
				Intent intent = new Intent();
				/* 开启Pictures画面Type设定为image */
				intent.setType("image/*");
				/* 使用Intent.ACTION_GET_CONTENT这个Action */
				intent.setAction(Intent.ACTION_GET_CONTENT);
				/* 取得相片后返回本画面 */
				startActivityForResult(intent, PHOTO_WITH_DATA);
				break;
			default:
				break;
			}

			mDialog.dismiss();
		}
	};

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		File file = null;
		Bitmap pic = null;
		if (resultCode == FragmentActivity.RESULT_OK) {
			hasPic = true;
			ivPic.setBackgroundResource(R.drawable.share_pic_have);
			switch (requestCode) {
			case PHOTO_WITH_CAMERA:// 获取拍摄的文件
				picPath = captureFile.getAbsolutePath();
				LogTools.info("PicPath:" + picPath);
				file = new File(picPath);
				pic = ComImgTools.decodeFile(file);
				// thumbimage.setImageBitmap(pic);
				LogTools.info("PicFrom:相机");
				break;

			case PHOTO_WITH_DATA:// 获取从图库选择的文件
				Uri uri = data.getData();
				String scheme = uri.getScheme();
				if (scheme.equalsIgnoreCase("file"))// miui的返回类型
				{
					picPath = uri.getPath();
					LogTools.info("PicPath:" + picPath);
					LogTools.info("PicFrom:文件,MIUI");
					file = new File(picPath);
					pic = ComImgTools.decodeFile(file);
					// thumbimage.setImageBitmap(pic);
				} else if (scheme.equalsIgnoreCase("content"))// 原生的返回类型
				{
					Cursor cursor = mContext.getContentResolver().query(uri,
							null, null, null, null);
					cursor.moveToFirst();
					picPath = cursor.getString(1);
					file = new File(picPath);
					pic = ComImgTools.decodeFile(file);
					LogTools.info("PicPath:" + picPath);
					LogTools.info("PicFrom:文件,原生");
					// thumbimage.setImageBitmap(pic);
				}
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	};
}
